package com.zmn.oms.zmn.business.impl.rework;

import com.github.ltsopensource.core.json.JSON;
import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.consts.GateTypeConsts;
import com.zmn.mos.common.dio.order.add.NormalOrderAddDIO;
import com.zmn.mos.common.dio.order.add.nest.OrderBaseInfo;
import com.zmn.mos.common.dio.order.add.nest.OrderDistributeMasterDIO;
import com.zmn.mos.common.dio.order.add.nest.OrderProductDIO;
import com.zmn.mos.common.dio.order.add.nest.UserDIO;
import com.zmn.mos.common.dro.order.OrderAddDRO;
import com.zmn.mos.dubbo.interfaces.order.NormalOrderRemoteService;
import com.zmn.oms.business.interfaces.work.tag.OrderTagBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.constant.OrderTagConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.tag.OrderTagAddDTO;
import com.zmn.oms.model.dto.work.masterwork.CompleteDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.master.OrderMaster;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.work.DistributeVO;
import com.zmn.oms.model.vo.work.ZsOrderDistributeVO;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.master.OrderMasterService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.rework.ZsReworkBService;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.WorkFlowContextBService;
import com.zmn.oms.zmn.normal.business.interfaces.work.masterwork.ZsNormalMasterWorkBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class ZsReworkBServiceImpl implements ZsReworkBService {

    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderProductService orderProductService;
    @Autowired
    private OrderMasterService orderMasterService;
    @Autowired
    private ZsNormalMasterWorkBService zsNormalMasterWorkBService;
    @Autowired
    private WorkFlowContextBService workFlowContextBService;
    @Autowired
    private OrderTagBService orderTagBService;

    @Reference(version = com.zmn.mos.dubbo.utils.DubboConsts.INTERFACE_VERSION, timeout = 10000, check = false)
    private NormalOrderRemoteService normalOrderRemoteService;

    /**
     * 返修新单
     * @param orderId
     * @param workId
     * @throws OmsBaseException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addReworkNewOrder(Long orderId, Long workId, Integer masterId) throws OmsBaseException {
        OrderWork reworkWork = orderWorkService.findMasterWorkDetail(orderId, workId, masterId);
        if (reworkWork == null) {
            throw new OmsBaseException("工单已被处理");
        }
        boolean isCancel = Objects.equals(reworkWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DISCARD) ||
                (Objects.equals(reworkWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_FAIL) && Objects.isNull(reworkWork.getCompleteTime()));
        if (isCancel) {
            throw new OmsBaseException("工单已取消，不可操作");
        }
        if (reworkWork.getStatus() > OrderStatusConsts.WORK_STATUS_VISIT) {
            throw new OmsBaseException("工单已完成，不可操作");
        }
        OrderDetail reworkDetail = orderDetailService.findOrderDetailByKey(orderId);
        List<OrderProduct> reworkProduct = orderProductService.listOrderProductByOrderId(orderId);
        List<OrderMaster> orderMaster = orderMasterService.listMasterByMasterIdList(orderId, workId, Lists.newArrayList(masterId));

        // 操作信息
        NormalOrderAddDIO normalOrderAddDIO = new NormalOrderAddDIO();
        normalOrderAddDIO.setOperator(reworkWork.getMasterName());
        normalOrderAddDIO.setOperatorId(reworkWork.getMasterId());
        normalOrderAddDIO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_MASTER);

        normalOrderAddDIO.setFinalPrice(reworkWork.getFinalPrice());
        normalOrderAddDIO.setServCategId(reworkWork.getServCategId());

        // 基础信息
        OrderBaseInfo orderBaseInfo = new OrderBaseInfo();
        orderBaseInfo.setPlat(reworkWork.getPlatWork());
        orderBaseInfo.setBizType(reworkWork.getBizType());
        // 返修新单指定渠道
        orderBaseInfo.setChannelId(OrderConsts.CHANNEL_ID_PLAT_REWORK_NEW_ORDER);
        orderBaseInfo.setType(OrderConsts.ORDER_TYPE_NEW);
        orderBaseInfo.setOriginalId(orderId);
        orderBaseInfo.setReceiveEntranceId(GateTypeConsts.GATE_APP_MASTER_ANDROID);
        normalOrderAddDIO.setOrderBaseInfo(orderBaseInfo);
        // 用户信息
        UserDIO userDIO = new UserDIO();
        userDIO.setUserId(reworkWork.getUserId());
        userDIO.setUserName(reworkDetail.getUserName());
        userDIO.setTelephone(reworkDetail.getTelephone());
        userDIO.setTelephone2(reworkDetail.getTelephone2());
        userDIO.setTelephone3(reworkDetail.getTelephone3());
        userDIO.setUserType(reworkDetail.getUserType());
        userDIO.setContactName(reworkDetail.getContactName());
        userDIO.setGender(reworkDetail.getGender());
        userDIO.setCityId(reworkWork.getCityId());
        userDIO.setCountyId(reworkDetail.getCountyId());
        userDIO.setStreetSource(reworkDetail.getStreetSource());
        userDIO.setStreetId(reworkDetail.getStreetId());
        userDIO.setStreet(reworkDetail.getStreet());
        userDIO.setAddress(reworkDetail.getAddress());
        userDIO.setLongitude(reworkDetail.getLongitude());
        userDIO.setLatitude(reworkDetail.getLatitude());
        normalOrderAddDIO.setUserDIO(userDIO);
        // 产品信息
        OrderProductDIO orderProductAddDIO = new OrderProductDIO();
        OrderProduct orderProduct = reworkProduct.get(0);
        Date dutyTime = new Date(DateUtil.getNowTimestampMillis() + 1000 * 60 * 10);
        orderProductAddDIO.setDutyTime(dutyTime);
        orderProductAddDIO.setBrandId(orderProduct.getBrandId());
        orderProductAddDIO.setServCategId(reworkWork.getServCategId());
        orderProductAddDIO.setCategId(orderProduct.getCategId());
        orderProductAddDIO.setProductId(orderProduct.getProductId());
        orderProductAddDIO.setShowProductId(orderProduct.getShowProductId());
        orderProductAddDIO.setNumber(orderProduct.getNumber());
        orderProductAddDIO.setRemark(orderProduct.getRemark());
        orderProductAddDIO.setFault(orderProduct.getFault());
        List<OrderProductDIO> orderProductList = Lists.newArrayList(orderProductAddDIO);
        normalOrderAddDIO.setOrderProductList(orderProductList);
        // 预派工程师
        OrderDistributeMasterDIO orderDistributeMasterDIO = new OrderDistributeMasterDIO();
        orderDistributeMasterDIO.setDistributeMasterId(reworkWork.getMasterId());
        DistributeVO distributeVO = new DistributeVO();
        ZsOrderDistributeVO autoDistributeMaster = new ZsOrderDistributeVO();
        autoDistributeMaster.setMasterId(reworkWork.getMasterId());
        autoDistributeMaster.setMasterName(reworkWork.getMasterName());
        autoDistributeMaster.setMasterPhone(orderMaster.get(0).getMasterPhone());
        autoDistributeMaster.setDistributeRelateWorkText("返修新单指定派");
        distributeVO.setAutoDistributeMaster(autoDistributeMaster);
        orderDistributeMasterDIO.setDistributeJsonStr(JSON.toJSONString(distributeVO));
        List<OrderDistributeMasterDIO> distributeMasterList = Lists.newArrayList(orderDistributeMasterDIO);
        normalOrderAddDIO.setDistributeMasterList(distributeMasterList);

        log.info("返修新单#normalOrderRemoteService#addOrder入参：[{}]", normalOrderAddDIO);
        ResponseDTO<OrderAddDRO> responseDTO = normalOrderRemoteService.addOrder(normalOrderAddDIO);
        log.info("返修新单#normalOrderRemoteService#addOrder出参：[{}]", responseDTO);
        if (!responseDTO.isSuccess()){
            throw new OmsBaseException(responseDTO.getMessage());
        }

        OrderAddDRO orderAddDRO = responseDTO.getData();
        Long newOrderId = orderAddDRO.getOrderId();

        // 返修单自动完成
        CompleteDTO completeDTO = new CompleteDTO();
        completeDTO.setOrderId(orderId);
        completeDTO.setWorkId(workId);
        completeDTO.setOperatorLogRemark("备注：返修单收费，系统自动完结并建返修新单，新单号：" + newOrderId);
        completeDTO.setOperator("系统");
        completeDTO.setOperatorId(1L);
        completeDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
        try {
            // 添加返修收费标签
            OrderTagAddDTO orderTagAddDTO = new OrderTagAddDTO();
            orderTagAddDTO.setOrderId(orderId);
            orderTagAddDTO.setWorkId(workId);
            orderTagAddDTO.setTagIdList(Lists.newArrayList(OrderTagConsts.TAG_ID_WORK_REWORK_CHARGE));
            orderTagBService.addOrderTag(orderTagAddDTO);

            zsNormalMasterWorkBService.completeOrder(completeDTO);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("[{}]返修单另外收费，自动完成异常:【{}】", orderId, e.getMessage());
        }

        workFlowContextBService.asyncAutoFlow(orderId, workId);

        return newOrderId;
    }
}
